const express = require('express')
const { json } = require('express/lib/response')
const router = express.Router()

const Order = require('../Schemas/OrderSchema')

router.post('/addOrder', (req, res) => {
    let key = req.body.key
    let order = req.body.order
    order.userid = req.body.userid
    if (key == 'cansel') {
        order.cansel = true
        order.done = false
        order.waitpay = false
    }
    else if (key == 'waitpay') {
        order.cansel = false
        order.done = false
        order.waitpay = true
    } else {
        order.cansel = false
        order.done = true
        order.waitpay = false
    }
    let adorder = new Order(order)
    adorder.save()
    res.json({
        code: '200',
        message: '添加订单成功'
    })
})

router.post('/getOrder', (req, res) => {
    let key = req.body.key
    let condi = {}
    if (key == 'cansel') {
        condi = { cansel: true }
    }
    else if (key == 'waitpay') {
        condi = { waitpay: true }
    } else {
        condi = { done: true }
    }
    Order.find(condi).then((o) => {
        res.json({
            code: 200,
            message: '查询订单成功',
            data: o
        })
    }).catch((err) => {
        res.json({
            code: 500,
            message: err
        })
    });
})

router.post('/deleteOrder', (req, res) => {
    Order.deleteOne({ _id: req.body._id }).then(() => {
        res.json({
            code: 200,
            message: '删除成功'
        })
    }).catch(() => {
        res.json({
            code: 500,
            message: "删除失败"
        })
    })
})

module.exports = router